package vn.nt.healthcare.server.ws.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import vn.nt.healthcare.server.ws.domain.Company;
import vn.nt.healthcare.server.ws.model.Customer;
import vn.nt.healthcare.server.ws.model.CustomerInfo;
import vn.nt.healthcare.server.ws.model.Pregnant;
import vn.nt.healthcare.server.ws.model.Push;
import vn.nt.healthcare.server.ws.repositories.CompanyRepository;
import vn.nt.healthcare.server.ws.service.PregnantService;

@Service("pregnantService")
@Transactional
public class PregnantServiceImpl implements PregnantService, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Autowired
	private CompanyRepository companyRepository;

	@Override
	public CustomerInfo findPregnantById(String companyId, int id) {
		Company company = companyRepository.findByCode(companyId);
		if (company != null) {
			Session session = null;
			try {
				session = ServiceHelper.openSession(company);
				Pregnant pre = (Pregnant) session.get(Pregnant.class, id);
				CustomerInfo result = initInfo(pre);
				return result;
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			} finally {
				ServiceHelper.closeSession(session);
			}
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<CustomerInfo> findAll(String companyId) {
		Company company = companyRepository.findByCode(companyId);
		if (company != null) {
			Session session = null;
			try {
				session = ServiceHelper.openSession(company);
				StringBuilder sql = new StringBuilder(
						"SELECT DISTINCT p FROM Pregnant p WHERE 1 = 1");
				Query query = session.createQuery(sql.toString());
				List<Pregnant> list = query.list();
				List<CustomerInfo> listInfos = new ArrayList<CustomerInfo>();
				if (!CollectionUtils.isEmpty(list)) {
					for (Pregnant pre : list) {
						CustomerInfo result = initInfo(pre);
						listInfos.add(result);
					}
				}
				return listInfos;
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			} finally {
				ServiceHelper.closeSession(session);
			}
		}
		return null;
	}

	@Override
	public boolean saveOrUpdatePregnant(String companyId, Pregnant pregnant) {
		// TODO Auto-generated method stub
		Company company = companyRepository.findByCode(companyId);
		if (company != null) {
			Session session = null;
			Transaction transaction = null;
			try {
				session = ServiceHelper.openSession(company);
				transaction = session.beginTransaction();
				session.saveOrUpdate(pregnant);
				transaction.commit();
				return true;
			} catch (Exception e) {
				// TODO: handle exception
				if (transaction != null)
					transaction.rollback();
				e.printStackTrace();
			} finally {
				ServiceHelper.closeSession(session);
			}
		}
		return false;
	}

	@Override
	public boolean removePregnant(String companyId, int id) {
		Company company = companyRepository.findByCode(companyId);
		if (company != null) {
			Session session = null;
			Transaction transaction = null;
			try {
				session = ServiceHelper.openSession(company);
				transaction = session.beginTransaction();
				Pregnant pre = (Pregnant) session.get(Pregnant.class, id);
				if (pre != null) {
					session.delete(pre);
				}
				transaction.commit();
				return true;
			} catch (Exception e) {
				if (transaction != null) {
					transaction.rollback();
				}
				e.printStackTrace();
			} finally {
				ServiceHelper.closeSession(session);
			}
		}
		return false;
	}

	@Override
	public boolean savePregnantAndPush(String companyId, Pregnant pregnant,
			String os, String token) {
		// TODO Auto-generated method stub
		Company company = companyRepository.findByCode(companyId);
		if (company != null) {
			Session session = null;
			Transaction transaction = null;
			try {
				session = ServiceHelper.openSession(company);
				transaction = session.beginTransaction();
				session.save(pregnant);
				Push push = new Push();
				push.setToken(token);
				push.setCreatedDate(new Date());
				push.setCustomerId(pregnant.getId());
				session.saveOrUpdate(push);
				transaction.commit();
				return true;
			} catch (Exception e) {
				// TODO: handle exception
				if (transaction != null)
					transaction.rollback();
				e.printStackTrace();
			} finally {
				ServiceHelper.closeSession(session);
			}
		}
		return false;
	}

	private CustomerInfo initInfo(Pregnant pre) {
		CustomerInfo result = new CustomerInfo();
		Customer customer = pre.getCustomer();
		
		result.setCity(customer.getCity());
		result.setStreet(customer.getStreet());
		result.setNr(customer.getNr());
		result.setState(pre.getState());
		result.setPeriod(pre.getPeriod());
		result.setFirstname(customer.getFirstname());
		result.setLastname(customer.getLastname());
		result.setAge(customer.getAge());
		result.setEmail(customer.getEmail());
		result.setPhone(customer.getPhone());
		result.setFemale_date(pre.getFemale_date());
		result.setBirthday(customer.getBirthday());
		result.setWeight(pre.getWeight());
		result.setHeight(pre.getHeight());
		result.setTypeBlood(pre.getTypeBlood());
		
		return result;
	}
}
